package com.tanhua.manage.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.tanhua.manage.domain.Admin;
import com.tanhua.manage.interceptor.AdminHolder;
import com.tanhua.manage.service.AdminService;
import com.tanhua.manage.vo.AdminVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@RestController
@RequestMapping("/system/users")
public class AdminController {

    @Autowired
    private AdminService adminService;

    /**
     * 获取验证码图片
     *    请求方式：GET verification
     *    业务：
     *      1、设置响应头
     *      2、调用hutool工具类，生成验证码图片
     *      3、获取图片中的验证码文字，写入redis
     *      4、已输出流的形式响应图片
     *    参数：
     *      uuid，httpservletResponse
     */
    @GetMapping("/verification")
    public void verification(String uuid, HttpServletResponse response) throws IOException {
        //1、设置响应头
        response.setDateHeader("Expires", 0);
        // Set standard HTTP/1.1 no-cache headers.
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        // Set IE extended HTTP/1.1 no-cache headers (use addHeader).
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        // Set standard HTTP/1.0 no-cache header.
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");
        //2、调用hutool工具类，生成验证码图片
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(299, 97);//生成验证码图片对象
        //3、获取验证码文字
        String code = lineCaptcha.getCode();
        //4、存入redis
        adminService.saveCap(uuid,code);
        //5、已输出流的形式响应图片
        lineCaptcha.write(response.getOutputStream());
    }

    /**
     * 用户登录
     *  POST  /login
     *  参数：
     *
     */
    @PostMapping("/login")
    public ResponseEntity login(@RequestBody Map<String,String> map) {
        return adminService.login(map);
    }

    /**
     * 获取当前登录用户的详情：
     *  POST    /profile
     *  在请求头中包含一个 Authorization 数据(token元素)
     *     Bearer token
     *  返回AdminVo
     */
    @PostMapping("/profile")
    public ResponseEntity profile() {
        Admin admin = AdminHolder.getAdmin();
        AdminVo vo = new AdminVo();
        BeanUtils.copyProperties(admin, vo);
        return ResponseEntity.ok(vo);
    }


    /**
     * 退出登录
     *  POST  /logout
     */
    @PostMapping("/logout")
    public ResponseEntity logout(@RequestHeader("Authorization") String token) {
        token = token.replace("Bearer ", "");
        return adminService.logout(token);
    }
}
